How to use Python Lambda functions: a 5 minute tutorial 您所在的位置:网站首页 key=lambda x:x[1] How to use Python Lambda functions: a 5 minute tutorial

How to use Python Lambda functions: a 5 minute tutorial

2024-07-12 17:05| 来源: 网络整理| 查看: 265

How to implement Python lambda functions

A lambda function is declared differently than a normal function. In Python, lambda functions have the following unique characteristics:

It can only contain expressions It cannot include statements in its body It is written as a single line It does not support type annotations It can be immediately invoked

A lambda function in Python uses the following basic syntax. As we mentioned before, we use the lambda keyword to create a simple function in a Python expression.

lambda arguments: expression

A lambda expression can have any number of arguments (including none). For example:

lambda: 1 # No arguments lambda x, y: x + y lambda a, b, c, d: a*b + c*d

In the following example, we use a lambda function to replace an area function:

lambda x: x[0]*x[1]

The lambda keyword identifies the lambda expression. In the above example, x is the only parameter. The colon ends the parameter list and introduces the body of the function.

To use this expression properly, you place it wherever you might normally use a function object. This piece of code below creates a temporary, anonymous function object and passes it into the sorted function, which then performs the sort.



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有